package org.linloong.modules.apis.common.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.linloong.core.result.Result;
import org.linloong.modules.apis.common.dto.DownloadDTO;
import org.linloong.modules.apis.common.service.DownloadService;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.StandardOpenOption;
import java.util.List;


/**
 * @author dbo
 */
@Slf4j
@RestController
@Tag(name = "下载", description = "下载文件")
@RequestMapping("/download")
@RequiredArgsConstructor
public class DownloadController {

    private final DownloadService downloadService;


    @PostMapping(value = "/zip")
    @Operation(summary = "报告导出", description = "根据提供的下载数据列表，生成压缩包并返回")
    public Result<String> downloadZip(@RequestBody List<DownloadDTO> data) {
        return Result.success(downloadService.downloadZip(data));
    }

//    @GetMapping(value = "/report/word/{wordId}")
    public void downloadZip(@PathVariable Long wordId, HttpServletResponse response) throws IOException {
        String path = System.getProperty("user.dir") + File.separator + "tempFile" + File.separator + wordId + File.separator + "报告.docx";
        if (!FileUtil.exist(path)) {
            response.setStatus(404);
            return;
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Location", URLUtil.encode("报告.docx"));
        response.setHeader("Content-Disposition", "attachment; filename=" + URLUtil.encode("报告.docx"));
        try (FileChannel readChannel = FileChannel.open(new File(path).toPath(), StandardOpenOption.READ)) {
            long len = readChannel.size();
            long position = readChannel.position();
            try (WritableByteChannel writeChannel = Channels.newChannel(response.getOutputStream())) {
                readChannel.transferTo(position, len, writeChannel);
            }
        }
    }
}
